package com.moarea.app.exception;

import com.moarea.app.lang.model.ResultObject;
import com.moarea.app.util.JsonUtil;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 功能：全局异常处理
 * <p>
 * 作者：嵇众
 * <p>
 * 时间：2017-07-09
 */
@Component
public class GlobalCustomExceptionResolver extends DefaultHandlerExceptionResolver {

    private static Logger log = Logger.getLogger(GlobalCustomExceptionResolver.class);

    @Override
    protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        if (request.getHeader("accept") != null
                && (request.getHeader("accept").contains("application/json")
                || (request.getHeader("X-Requested-With") != null
                && request.getHeader("X-Requested-With").contains("XMLHttpRequest")))) {
            ResultObject ro = ResultObject.createInstance(false);
            ro.setSuccess(false);
            if (ex instanceof GlobalCustomException) {
                ro.setMessage(((GlobalCustomException) ex).getCustomMessage());
            } else {
                ro.setMessage(String.format("系统发生异常:%1$s", ex.getMessage()));
                log.error(String.format("系统发生异常:%1$s", ex.getMessage()));
                ex.printStackTrace();
            }
            try {
                JsonUtil.writeJson(request, response, ro);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
        return super.doResolveException(request, response, handler, ex);
    }
}
